package com.eshop.controller;

import com.eshop.pojo.Pager;
import com.eshop.pojo.ProductInfo;
import com.eshop.pojo.Type;
import com.eshop.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/type")
public class TypeController {
    @Autowired
    private TypeService service;

    @RequestMapping(value = "/getType/{flag}",method = RequestMethod.POST)
    @ResponseBody//将返回类型转换成json类型
    public List<Type> getType(@PathVariable("flag") int flag){
        List<Type> typeList = service.selectAll();
        if (flag == 1){
            Type type = new Type();
            type.setId(0);
            type.setName("请选择...");
            typeList.add(0,type);
        }
        return typeList;
    }

    @ResponseBody
    @RequestMapping("/list")  //自动加载
    public List<Type> getList(Type type){
        List<Type> typeList;
        if ( type.getName()==null || type.getName().equals("请输入关键字...")) {
            typeList = service.selectAll();
        } else {
            typeList = service.selectByObject(type);
        }
        return typeList;
    }

    @ResponseBody
    @RequestMapping(value = "/addType",produces = "text/html;charset=UTF-8") //增加商品类型
    public String addType(Type type){
        if ( service.selectByName(type.getName()) > 0 )
            return "{\"success\":\"false\",\"message\":\"已有此类型！\"}";
        service.add(type);
        return "{\"success\":\"true\",\"message\":\"新类型添加成功！\"}";
    }

    @ResponseBody
    @RequestMapping(value = "/editType",produces = "text/html;charset=UTF-8")
    public String editType(Type type){
        //System.out.println("------------"+type+"------------");
        try {
            //System.out.println(type.getId());//调试
            service.update(type);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"success\":\"false\",\"message\":\"更新类型失败！\"}";
        }
        return "{\"success\":\"true\",\"message\":\"更新类型成功！\"}";
    }

    @ResponseBody
    @RequestMapping(value = "/deleteType", produces = "text/html;charset=UTF-8")
    public String deleteType(@RequestParam(value = "id") int id){
        int count = 0 ;
        try {
            count = service.deleteType(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (count>0) {
            return "{\"success\":\"true\",\"message\":\"成功删除 1 个类型！\"}";
        }
        return "{\"success\":\"false\",\"message\":\"尚有该类型的产品，不可删除！\"}";
    }
}
